/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2016 All Rights Reserved.
 */
package com.alipay.study.core.security.login;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alipay.study.common.contact.security.SecurityWebContact;
import com.alipay.study.common.util.date.DateUtil;
import com.alipay.study.common.util.log.LogUtil;

/**
 * 
 * @author wb-qlj205528
 * @version $Id: LoginFailhandler.java, v 0.1 2016年11月10日 下午4:05:50 wb-qlj205528 Exp $
 */
@Component
public class LoginFailhandler extends ExceptionMappingAuthenticationFailureHandler implements
                                                                                  AuthenticationFailureHandler {

    /**
     * 
     */
    private static Logger      LOGGER = Logger.getLogger(LoginFailhandler.class);

    /***
     * security contact
     */
    @Autowired
    private SecurityWebContact securityWebContact;

    /**
     * 是否已经将defaultFailureUrl初始化
     */
    private static boolean     init   = false;

    /**
     * 初始化---第一次请求时初始化
     */
    public void init() {
        setDefaultFailureUrl(securityWebContact.getLoginPage());
        init = true;
    }

    /** 
    * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
    */
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException,
                                                                          ServletException {
        LogUtil.warn(LOGGER, DateUtil.formatDefault(new Date()), "    用户  ",
            request.getParameter(securityWebContact.getUsernameParam()), "  登录失败");
        if (!init) {
            init();
        }
        super.onAuthenticationFailure(request, response, exception);
    }

}
